<template>
  <div class="bscroll-menu">
    <div class="wrapper_left" ref="wrapper_left">
      <div class="content-left">
        <div v-for="(menu, idx) in categoryTree" :key="idx" :class="{ currentIndex: idx === currentIndex }"
             ref="leftMenuItem" @click="onClickLeftMenus(idx,$event)">
          <div>{{ menu.name }}</div>
        </div>
      </div>
    </div>

    <div class="wrapper_right" ref="wrapper_right">
      <div class="content-right">
        <div v-for="(menu, idx) in categoryTree" :key="idx" ref="rightMenuItem">
          <van-cell :value="menu.name" class="category-title"></van-cell>
          <van-grid :column-num="3" :icon-size="70" clickable>
            <van-grid-item v-for="(sub, i) in menu.children" :key="i" :icon="$fullUrl(sub.img)"
                           :text="sub.name" :to="{
                                name: 'goodsList',
                                params: { categoryId: sub.id },
                            }"></van-grid-item>
          </van-grid>
        </div>
        <div style="height:100px"></div>
      </div>
    </div>
  </div>
</template>

<script>
import BScroll from "better-scroll"; //导入滚动模块
import * as CategoryAPI from "@/api/category.js"; //导入API封装模块
import {array2Tree} from "@/utils/tools";

export default {
  data() {
    return {
      categoryTree: [], //类别菜单名称列表，注意其数据结构
      topHeight: [], //保存每个分类区域的top位置值
      scrollY: 0, //时时查询当前Y轴的高度
      clickEvent: false
    };
  },
  computed: {
    currentIndex() {
      // 当 scrollY 发生改变时，计算左菜单的激活项
      for (let i = 0; i < this.topHeight.length; i++) {
        let top1 = this.topHeight[i];
        let top2 = this.topHeight[i + 1];
        if (!top2 || this.scrollY >= top1 && this.scrollY < top2) {
          return i;
        }
      }
      return 0;
    }
  },
  created() {
    this.init();
  },
  methods: {
    // 查询左侧菜单的分类内容
    init() {
      CategoryAPI.getCategoryAll().then(result => {
        this.categoryTree = array2Tree(result.data, 0);
        // $nextTick用来在下次DOM更新循环结束之后执行延迟回调
        this.$nextTick(() => {
          this._initBScroll(); // 初始化better-scroll
          this._calculateRightHeight(); // 初始化右边菜单项的高度数组值
        });
      });
    },

    // 初始化better-scroll
    _initBScroll() {
      //初始左侧菜单滚动
      this.leftBscroll = new BScroll(this.$refs.wrapper_left, {
        click: true,
        mouseWheel: true,
      });

      //初始右侧菜单滚动
      this.rightBscroll = new BScroll(this.$refs.wrapper_right, {
        click: true,
        mouseWheel: true,
        probeType: 3, // 实时派发 scroll 事件
      });
      //设置右侧对象滚动时的回调函数
      this.rightBscroll.on("scroll", (pos) => {
        this.scrollY = Math.abs(Math.round(pos.y)) + 6; //另加了一个偏移
      });
    },

    // 初始化右边菜单的高度
    _calculateRightHeight() {
      let itemArray = [];
      let top = 0;
      itemArray.push(top);
      let list = this.$refs.rightMenuItem;

      // 将 list 转换为普通数组进行遍历，记录每个元素的高度
      Object.values(list).forEach((item) => {
        top += item.clientHeight;
        itemArray.push(top);
      });
      this.topHeight = itemArray;
    },

    // 单击左菜单中的某一项后，右侧区域滚动到对应右菜单项
    onClickLeftMenus(index, event) {
      console.log(event);
      this.clickEvent = true;
      if (!event._constructed) {
        return;
      } else {
        let list = this.$refs.rightMenuItem;
        let el = list[index];
        this.rightBscroll.scrollToElement(el, 300);
      }
    },
  },
};
</script>

<style lang="less" scoped>
.category-title {
  text-align: left;
  font-size: 16px;
  color: #333;
  font-weight: bold;
  padding: 10px;
}

.currentIndex {
  background: #fff;
  color: red;
  font-weight: bold;
}

.bscroll-menu {
  display: flex;
  position: absolute;
  // top: 46px;
  // bottom: 50px;
  //width: 100%;
  height: 100%;
  overflow: hidden;
}

.wrapper_left {
  .content-left {
    display: flex;
    flex-direction: column;
    width: 80px;
    background: #f3f5f7;
    font-size: 16px;
    text-align: center;
    line-height: 46px;
  }
}

.wrapper_right {
  .content_right {
    display: flex;
    flex-direction: column;
    background: #fff;
  }
}
</style>
